<?php
class Db_Location
{
    private static $_cities;

    public function getAllLocation($delcache = false){
        if(ArrCache::is_not_cached('location_arr',0,'',$delcache)){
            self::$_cities = DB::fetch_all("SELECT * FROM location", __FILE__ . ' line ' . __LINE__);
            if(!$delcache){
                ArrCache::set(array('all_location'	=>self::$_cities));
            }
		}else{
			self::$_cities	= ArrCache::$arr_cache['all_location'];
			unset(ArrCache::$arr_cache['all_location']);
		}
    }
    public static function listLocationPopular(){
        static $locations;
        $condition = 'id_citiesfather = 0 ORDER by orders ASC  LIMIT 10';
        $key = hash('crc32b',$condition);

        if(!isset($locations[$key])){
            if($condition){
                $condition = 'WHERE '.$condition;
            }
            $locations[$key] =  DB::fetch_all_array("SELECT id FROM location $condition ", __FILE__ . ' line ' . __LINE__);
        }
        self::get_cities();
        $arrayLocation = array();
        foreach($locations[$key] as $ls){
           //var_dump($ls['name']);
           $arrayLocation[] = CGlobal::$all_cities[$ls['id']];
        }
        return $arrayLocation;
    }

    public static function listLocationPopularLimit($num, $array){
        static $locations;
        $condition = ' id_citiesfather = 0 ';
        if($array){
             $condition .= ' AND id NOT IN ('.implode(',',$array).') ';
        }
        if($num){
             $condition .= ' LIMIT '.$num;
        }
        $key = hash('crc32b',$condition);

        if(!isset($locations[$key])){
            if($condition){
                $condition = 'WHERE '.$condition;
            }
            $locations[$key] =  DB::fetch_all_array("SELECT id FROM location $condition ", __FILE__ . ' line ' . __LINE__);
        }
        self::get_cities();
        $arrayLocation = array();
        foreach($locations[$key] as $ls){
           //var_dump($ls['name']);
           $arrayLocation[$ls['id']] = CGlobal::$all_cities[$ls['id']];
        }
        return $arrayLocation;
    }

    public static function listLocationByArrayId($array){
        static $locations;
        if(is_array($array) && !empty($array)){
            $condition = 'id_citiesfather = 0 AND id IN ('.implode(',',$array).') ';
        }else{
            $condition = 'id_citiesfather = 0 LIMIT 10 ';
        }

        $key = hash('crc32b',$condition);

        if(!isset($locations[$key])){
            if($condition){
                $condition = 'WHERE '.$condition;
            }
            $locations[$key] =  DB::fetch_all_array("SELECT id FROM location $condition ", __FILE__ . ' line ' . __LINE__);
        }
        self::get_cities();
        $arrayLocation = array();
        foreach($locations[$key] as $ls){
           //var_dump($ls['name']);
           $arrayLocation[$ls['id']] = CGlobal::$all_cities[$ls['id']];
        }
        return $arrayLocation;
    }
    public static function &getAllCities() {
        if(!isset(self::$_cities))
            self::getAllLocation(true);
        return self::$_cities;
    }

    public static function getAllRootCities($show_all=true) {
        static $_cities;
        if(!isset($_cities)) {
            $_cities = self::getAllCities();
            foreach($_cities as $k=>&$city){
                if($show_all===true){//show all
                    if(0!=$city["id_citiesfather"])
                        unset($_cities[$k]);
                }else{//show only active
                    if((0!=$city["id_citiesfather"])&&($city["active"]==0))
                        unset($_cities[$k]);
                }
            }
            $_cities = array_values($_cities);
        }
        return $_cities;
    }

    public static function showDataCities($show_all=true) {
        $cities = self::getAllRootCities($show_all);
        foreach($cities as $city){
            $cities_show[$city["id"]] = $city["name"];
        }
        return $cities_show;
    }

    public static function showLocationFullName($id) {
        $_cities = self::getAllCities();
        $names = array();
        while($id && isset($_cities[$id])){
            $names[] = $_cities[$id]['name'];
            $id = $_cities[$id]['id_citiesfather'];
        }
        return $names;
    }

    public static function getParentId($child_id) {
        return DB::fetch('SELECT id_citiesfather FROM location WHERE id='. $child_id, 'id_citiesfather', 0, __FILE__ . ' line ' . __LINE__);
    }

    public static function getCitiesByParent($parent=0,$show_all=true) {
        static $_cities;
        if(!isset($_cities))
            $_cities = &self::getAllCities();
        $cities = array();
        foreach($_cities as $city){
            if($show_all===true){//show all
                if(($city["id_citiesfather"]==$parent))
                    $cities[] = $city;
            }else{//show only active
                if(($city["id_citiesfather"]==$parent)&&($city["active"]==1))
                    $cities[] = $city;
            }
        }
        return $cities;
    }

    public static function getAllCitiesByLevel($level=1,$show_all=true) {
        $cities = self::getAllRootCities();
        for($i=0; $i<$level; $i++) {
            $parents = $cities;
            $cities = array();
            foreach($parents as $city) {
                array_splice($cities, count($cities), 0, self::getCitiesByParent($city["id"],$show_all));
            }
        }
        return $cities;
    }

    public static function addSubLocation($parent_id,$level,&$show,$show_all=true){
        $level++;

        $area=array(1=>'Bắc',2=>'Trung',3=>'Nam');
        $status=array(1=>'Hiện',0=>'<font color=red>Ẩn</font>');

		$location = Db_Location::getCitiesByParent($parent_id,$show_all);
		if($location !== false){
			foreach($location as $loc){
                $loc["name"] = str_repeat("---------", ($level-1)).$loc["name"];
                if($loc['id_area']!=0){
                    $loc['id_area']=$area[$loc['id_area']];
                }else{
                    $loc['id_area']='';
                }
                $loc['active']=$status[$loc['active']];
				$show[] = $loc;
				self::addSubLocation($loc["id"],$level,$show);
			}
		}
	}

    public static function showLocationPagination($offset,$length,$show_all=true){
        self::addSubLocation(0,0,$show,$show_all);
        return array_splice($show, $offset, $length);
    }

    public static function delLocationById($id) {
        return DB::delete_id('location', $id, __FILE__ . ' line ' . __LINE__);
    }

    public static function delLocations($ids) {
        return DB::delete('location', 'id IN (' . implode(',', $ids) . ')', __FILE__ . ' line ' . __LINE__);
    }

    public static function insert($location) {
        if(!empty($location['latitude']) && !empty($location['longitude'])){
            $slug = strtolower(String::_name_cleaner(Unicode::stripUnicode($location['name'] ),'-'));
            $location['map_img'] = Db_Hotel::setMapImg($slug . '-map' ,$location['latitude'], $location['longitude'], 277, 277, 14, 0);
        }
        return DB::insert('location', $location, false, __FILE__ . ' line ' . __LINE__);
    }

    public static function update($location, $id) {
        if(!empty($location['latitude']) && !empty($location['longitude'])){
            $slug = strtolower(String::_name_cleaner(Unicode::stripUnicode($location['name'] ),'-'));
            $locationx = self::getLocationById($id);
            if (!empty($locationx['map_img'])){
                $location['map_img'] = Db_Hotel::setMapImg($slug . '-map' ,$location['latitude'], $location['longitude'], 277, 277, 14, $locationx['map_img']);
            }else{
                $location['map_img'] = Db_Hotel::setMapImg($slug . '-map' ,$location['latitude'], $location['longitude'], 277, 277, 14, 0);
            }
        }
        return DB::update_id('location', $location, $id, __FILE__ . ' line ' . __LINE__);
    }

    public static function getLocationByParentId($parent_id) {
        $parent_id = (int)$parent_id;
        return DB::fetch_for_show_smarty("SELECT id,name FROM location Where id_citiesfather=$parent_id","id","name", __FILE__ . ' line ' . __LINE__);
    }

    public static function getLocationById($id) {
        $_cities = self::getAllCities();
        return $_cities[$id];
    }

    public static function getLocaltionNameById($id){
        $_cities = self::getAllCities();
        return $_cities[$id]['name'];
    }

    /**
     * @static lấy danh sách các thành phố theo điều kiện
     * @param string $limit
     * @param string $condition
     * @return mixed
     */
    public static function listIdLocation($limit='', $condition=''){
        $key = hash('crc32b', $condition.$limit);
        if($condition){
             $condition = 'WHERE '.$condition;
        }
        $data =  DB::fetch_all_array("SELECT id FROM location $condition $limit", __FILE__ . ' line ' . __LINE__);
        $arrId = array();
        if($data !== null){
            foreach($data as $t){
                $arrId[]=$t['id'];
            }
        }
        return $arrId;
    }

    public static function get_cities($delcache = false){
        if(ArrCache::is_not_cached('city_arr',0,'',$delcache)){
            if(!$delcache){
                //added for All Cities
                CGlobal::$all_cities[0] = array(
                    "id" 	 => 0,
                    "name" 	 => "Toàn quốc",
                    "root" 	 => 1,
                    "bkname" => "Toan-quoc",
                    "id_citiesfather"=>0
                );

                $sql_str = "SELECT id, name, id_citiesfather, id_area, orders, active, img_url, latitude, longitude, map_img FROM ".TABLE_PREFIX."location WHERE active=1 ORDER by name ASC";
                $result  = DB::query($sql_str);
                $aryDistricts = array();

                while($city = mysql_fetch_assoc($result)){
                    $city["bkname"] = String::safe_title($city["name"]);

                    CGlobal::$all_cities[$city['id']] 			= $city;
                    CGlobal::$cities_name[strtolower($city['bkname'])] 			= $city;
                    CGlobal::$cities_list [$city['id_area']][] 	= $city;

                    //add for districts
                    if($city['id_citiesfather'] > 0){
                        $aryDistricts['id'] = $city['id'];
                        $aryDistricts['name'] = $city['name'];
                        $aryDistricts['id_citiesfather'] = $city['id_citiesfather'];
                        $aryDistricts['bkname'] = $city["bkname"];
                        CGlobal::$all_districs[$city['id_citiesfather']][$city['id']] 			= $aryDistricts;
                    }
                }

                ArrCache::set(array('array_city'=>CGlobal::$all_cities,'array_districs'=>CGlobal::$all_districs,'cities_list'=>CGlobal::$cities_list,'city_name'=>CGlobal::$cities_name));
            }else{
                foreach (CGlobal::$my_server as $server){//Tạo lại file js cho city
                    @fopen("http://$server/citygen.php","r");
                }
            }
        }
        else{
            $city_arr	 			= ArrCache::get();

            CGlobal::$all_cities  	= $city_arr['array_city'];
            CGlobal::$cities_list 	= $city_arr['cities_list'];
            CGlobal::$all_districs 	= $city_arr['array_districs'];
            CGlobal::$cities_name 	= $city_arr['city_name'];
        }
    }
    function getNamebyId($id){
        if($id){
            $result = DB::select('location', 'id = '.$id);
            return $result[0]['name'];
        }
        return '';
    }

    public static function getCityNotDistrict($id){
        $city_each = CGlobal::$all_cities[$id];
        $city = ($city_each["id_citiesfather"] != 0) ? CGlobal::$all_cities[$city_each["id_citiesfather"]] : $city_each;
        return $city;
    }
}
